<?php if (defined("YTDJ") or die()); 

Class Main {
	
	/**
	 * Contains the current module of the page
	 *
	 * @var string
	 */
	var $module;
	
	/**
	 * Contains the current task of the module
	 *
	 * @var string
	 */
	var $task;
	
	/**
	 * The controller class
	 *
	 * @var Controller
	 */
	var $controller;
	
	
	/**
	 * Constructor
	 *
	 * @param string $module
	 */
	function __construct($module, $task) {
		$this->module = $module;
		$this->task = $task;
	}
	
	static function render($module, $task) {
		$dispatcher = new Main($module, $task);
		$dispatcher->run(); 
	}
	
	function run() {
		// check whether controller exists
		$controllerfile = "modules/{$this->module}/{$this->module}.controller.php";
		if (!file_exists($controllerfile)) {
			Main::error("No controller file found for module $this->module");
		}
		
		// create controller class
		$controllerclassname = $this->module."Controller";
		if (!class_exists($controllerclassname)) {
			include($controllerfile);
		}
		if (!class_exists($controllerclassname)) {
			Main::error("No controller class found for module $this->module");
		}
		$this->controller = new $controllerclassname($this->module, $this->task);
		
		// execute task
		if (!method_exists($this->controller, $this->task)) {
			Main::error("No method found for task $this->task");
		}
		$this->controller->{$this->task}();
	}
	
	/**
	 * Die with an error
	 *
	 * @param string $msg
	 */
	function error($msg) {
		die($msg);
	}
	
	/**
	 * Outputs website
	 *
	 */
	function write($html) {
		// TODO: Compress html
		echo $html;
	}
}

?>